<?php
namespace app\api\controller;

use think\Lang;
use think\Response;
use think\Controller;

class Crontab extends Controller
{

    /**
     * 初始化方法,最前且始终执行
     */
    public function _initialize()
    {
        // 只可以以cli方式执行
        if (!$this->request->isCli())
            die ('this script only work at client!');
        parent::_initialize();
        // 清除错误
        error_reporting(0);
        // 设置永不超时
        set_time_limit(0);
    }

    public function table() {
        // echo "开始执行数据库异步持久化...\r\n";
        // echo "数据拉取中...";     
        $keys = \think\Cache::store('redis')->keys("crontab:table:*");
        // echo "共获取到 ".count($keys). " 个数据需要同步，分别为：".implode(",", $keys)." \r\n";        
        $tables = count($keys) > 3 ? array_rand($keys, 3) : array_keys($keys);
        // echo "随机取出 10 个数据表同步\r\n";

        foreach ($tables as $key => $name) {
            $data = [];
            $table = explode(":", $keys[$name]);
            $table = end($table);
            for ($i=0; $i < 100; $i++) { 
                $val = \think\Cache::store('redis')->Lpop($keys[$name]);
                if(!$val) continue;
                $ret = \think\Db::name($table)->insert(json_decode($val, true));
                if($ret === false) {
                    $data[] = $val;
                }                  
            }
            if($data) \think\Cache::store('redis')->rPush($key, ...$data);

            echo "[ ".$table." ] 成功插入 ".$ret." 条数据。";
        }
        return "数据同步成功...\r\n";
    }

    public function execute() {
        echo "\r\n method execute runing...";
        $keys = \think\Cache::store('redis')->keys("crontab:app:*");
        foreach ($keys AS $key) {
            list(,,$model, $method) = explode(":", $key);
            $data = [];
            for ($i=0; $i < 20; $i++) { 
                $val = \think\Cache::store('redis')->Lpop($key);
                if(!$val) continue;
                $ret = model($model, 'service')->$method(json_decode($val, true));
                if ($ret === false) {
                    $data[] = $val;
                }
            }
            if($data) \think\Cache::store('redis')->rPush($key, ...$data);
        }
        return true;
    }

    /* 删除日志文件 */
    public function clear_log() {
        echo "\r\n 查找日志文件中...";
        \fast\File::unlinkDir(LOG_PATH);
        return "日志文件清理执行完毕\r\n";
    }

    public function live()
    {
        $sqlmap = [];
        $sqlmap['status'] = 'normal';
        $sqlmap['end_time'] = ['lt',time()];
        $rows = model('live/live', 'service')->lists($sqlmap, 20, 0, 'id desc');
        foreach ($rows as $row) {
            echo "\r\n live finished ...<hr/>";
            model('live/live', 'service')->finished($row['id']);
        }
        return true;
    }
}